'''
Created on Mar 2, 2013

@author: Gabriel
'''
import re
import mc
import db

VIDEO_EXTENSIONS_PATTERN = ".*\.mkv|.*\.avi|.*\.mpg"


def __isVideoFile(path):
    return re.match(VIDEO_EXTENSIONS_PATTERN, str(path), re.IGNORECASE)

def __isDirectory(path):
    return mc.GetDirectory(path)

def listVideos(directory):
    print("IN listVideos")
    videos = []
    entries = mc.GetDirectory(directory)
    if entries :
        sortedEntries = sorted(entries, key=lambda entry: str(entry.GetLabel()))
        for entry in sortedEntries :
            print("VIDEOS")
            print(entry.GetPath())
            if __isDirectory(entry.GetPath()) :
                videos.extend(listVideos(str(entry.GetPath())))
            elif __isVideoFile(entry.GetPath()) :
                videos.append(str(entry.GetPath()))
    print("OUT listVideos")
    return videos


def listSeries(directory):
    print("IN listSeries")
    series = []
    entries = mc.GetDirectory(directory)
    # First level directories are the series, subsequent are seasons
    for entry in entries :
        print("SERIES")
        print(entry.GetPath())
        if __isDirectory(entry.GetPath()) : 
            serie = {'name':str(entry.GetLabel()), 'currentEpisode':0, 'episodes':listVideos(str(entry.GetPath()))}
            series.append(serie)
    print("OUT listSeries")
    return series


def build():
    print("IN build")
    baseDir = "smb://MYBOOKLIVE/Public/Shared Videos"

    database = {}
    
    moviesDir = "Movies"
    tvShowsDir = "TV"

    database['shows'] = listSeries(baseDir + '/' + tvShowsDir)
    database['movies'] = listSeries(baseDir + '/' + moviesDir)
    
    print(database)
    db.DatabaseMgr().createDatabase(database)    
    print("OUT build")
